from django.shortcuts import render

# Create your views here.
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import SKUSerializer
from . import constants
from .models import User
from . import serializers
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.


class UserView(CreateAPIView):
    """注册"""

    # 指定序列化器
    serializer_class = serializers.CreateUserSerializer


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


class UserDetailView(RetrieveAPIView):
    # 指定权限：只有登录用户才能访问该接口
      permission_classes = [IsAuthenticated]

      serializer_class = serializers. UserDetailSerializer

      """
       因为目前没有定义get方法，没有传递pk给RetrieveAPIView
       但是，RetrieveAPIView里面的get_object()方法需要得到当前的登录用户是谁
       所以重写这个方法，告诉RetrieveAPIView里面的get_object()方法，当前的登录用户是谁
       :return:
       """
      def get_object(self):
        # def get(self, request):
        #       """提供用户基本信息
        #       查询出当前登录用户user数据
        #       使用序列化器序列化user数据
        #       响应数据
        #       """
        #       pass
          return self.request.user

class EmailView(UpdateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.EmailSerializer
    def get_object(self):
        return self.request.user

class VerifyEmailView(APIView):
    def get(self,request):
        token= request.query_params.get('token')
        if token is None:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '无效token'}, status=status.HTTP_400_BAD_REQUEST)
        user.email_active = True
        user.save()
        return Response({'message':'OK'})



class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowseHistoryView(CreateAPIView):
    """用户浏览记录接口"""

    # 指定权限
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = serializers.UserBrowseHistorySerializer

    def get(self, request):
        """读取用户浏览记录
        """
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('history')

        # 查询所有的浏览记录数据
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        # 存放浏览记录sku的容器
        sku_list = []
        # 遍历出sku_id中的sku_id,使用sku_id查询sku
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 创建序列化器对象，同时实现序列化
        serializer = SKUSerializer(sku_list, many=True)

        # 响应
        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    """
    重写父类的post方法：重写之后，对于用户的校验，查询，响应都不需要我们再次写代码
    只需要专注于自己新加的业务逻辑即可
    """

    def post(self, request, *args, **kwargs):

        # 得到父类处理登录请求后的响应对象
        response = super(UserAuthorizeView, self).post( request, *args, **kwargs)
        # 得到父类的序列化器对象
        serializer = self.get_serializer(data=request.data)
        # 再次校验
        if serializer.is_valid():
            # 得到校验之后的用户信息
            user = serializer.object.get('user') or request.user
            # 实现合并
            response = merge_cart_cookie_to_redis(request=request, response=response, user=user)
        #返回最后的结果
        return response

        # """
        #  serializer = self.get_serializer(data=request.data)
        #
        # if serializer.is_valid():
        #     user = serializer.object.get('user') or request.user
        #     token = serializer.object.get('token')
        #     response_data = jwt_response_payload_handler(token, user, request)
        #     response = Response(response_data)
        #     if api_settings.JWT_AUTH_COOKIE:
        #         expiration = (datetime.utcnow() +
        #                       api_settings.JWT_EXPIRATION_DELTA)
        #         response.set_cookie(api_settings.JWT_AUTH_COOKIE,
        #                             token,
        #                             expires=expiration,
        #                             httponly=True)
        #     return response
        #
        # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST
        #
        # """

